﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Needle.Framework;
using Needle.Utils;
using System.IO;
using Needle.DevToolkit.Traits;
using Needle.DevToolkit.Services.UI;
using System.ComponentModel.Design;

namespace Needle.DevToolkit.Workspace
{

    public partial class WorkspaceController : Needle.Framework.Component
    {

        public event EventHandler WorkspaceLoaded;

        public WorkspaceController()
        {
            InitializeComponent();
        }

        public WorkspaceController(IContainer container)
        {
            container.Add(this);
            InitializeComponent();
        }

        public DirectoryInfo RootFolder { get; private set; }

        public IWorkspace Workspace { get; set; }

        public void LoadWorkspace(string folderPath)
        {
            if (!Directory.Exists(folderPath))
                throw new DirectoryNotFoundException(folderPath);
            RootFolder = new DirectoryInfo(folderPath);
            Workspace = new WorkspaceRoot
            {
                Name = RootFolder.Name,
                FolderPath = this.RootFolder.FullName
            };
            foreach (var info in RootFolder.GetFiles())
            {
                var file = new FileItem
                {
                    Name = info.Name,
                    FilePath = info.FullName,
                };
                Workspace.Items.Add(file);
            }
            foreach (var folder in this.RootFolder.GetDirectories("*", SearchOption.AllDirectories))
            {
                var relPath = FileSystem.MakePathRelativeTo(RootFolder, folder);
                CreateFolderItem(Workspace, relPath);
            }
            OnWorkspaceLoaded();
        }

        public void CreateFolderItem(IWorkspace Workspace, string relPath)
        {
            var parts = relPath.Split(new Char[] { Path.DirectorySeparatorChar });
            IParent parent = Workspace;
            for (int i = 0; i < parts.Length; i++)
            {
                var folder = (from x in parent.Items.GetItems<IFolder>()
                              where x.Name == parts[i]
                              select x).FirstOrDefault();

                if (folder == null)
                {
                    folder = new FolderItem
                    {
                        Name = parts[i],
                        FolderPath = String.Join(Path.DirectorySeparatorChar.ToString(), parts, 0, i + 1)
                    };
                    parent.Items.Add(folder);
                    var fullPath = Path.Combine(Workspace.FolderPath, relPath);
                    foreach (var filePath in Directory.GetFiles(fullPath))
                    {
                        FileInfo info = new FileInfo(filePath);
                        var file = new FileItem
                        {
                            Name = info.Name,
                            FilePath = info.FullName,
                        };
                        folder.Items.Add(file);
                    }
                }
                parent = folder;
            }
        }

        [Verb(MenuGroup.File, FileCommandId.Open, "Open Workspace")]
        private void WorkspaceOpen(ItemVerb verb, IItem item)
        {
            string folder = GetService<IFileChooser>().ChooseFolder(AppFileSystem.UserDataFolder.FullName);
            if (folder != null)
                LoadWorkspace(folder);
        }

        [Verb(ContextMenuGroup.WorkspaceExplorer, FileCommandId.Rename, "Rename Folder", RequiredTrait = typeof(IFolder))]
        private void RenameFolder(ItemVerb verb, IItem item)
        {
            Console.WriteLine("renaming folder " + item.GetTrait<IFolder>().FolderPath);
        }

        [Verb(ContextMenuGroup.WorkspaceExplorer, FileCommandId.Rename, "Rename File", RequiredTrait = typeof(IFile))]
        private void RenameFile(ItemVerb verb, IItem item)
        {
            Console.WriteLine("Rename file " + item.GetTrait<IFile>().FilePath);
        }

        [Verb(ContextMenuGroup.WorkspaceExplorer, FileCommandId.Custom, "Open Solution", RequiredTrait = typeof(IFile))]
        private void OpenSolution(ItemVerb verb, IItem item)
        {
            var file = new FileInfo(item.GetTrait<IFile>().FilePath);
            if (file.Extension.ToLower() != ".sln")
                throw new InvalidOperationException("Not a solution file");

            var parser = new SolutionFileParser(file.FullName);
            var solution = parser.Parse();
            var parent = item.GetTrait<INestedItem>().Parent;
            var itemIndex = parent.Items.IndexOf(item);
            parent.Items.Remove(item);
            parent.Items.Insert(itemIndex, solution);
        }

        protected virtual void OnWorkspaceLoaded()
        {
            EventHandler handler = WorkspaceLoaded;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }


    }
}
